package com.sdkj.controller.materials.getmaterials;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sdkj.controller.base.BaseController;
import com.sdkj.entity.Page;
import com.sdkj.entity.User;
import com.sdkj.util.AppUtil;
import com.sdkj.util.ObjectExcelView;
import com.sdkj.util.Const;
import com.sdkj.util.PageData;
import com.sdkj.util.Tools;
import com.sdkj.util.Jurisdiction;
import com.sdkj.service.activiti.ActTaskService;
import com.sdkj.service.materials.getmaterials.ApplyGetMaterialsDetailService;
import com.sdkj.service.materials.getmaterials.ApplyGetMaterialsService;
import com.sdkj.service.system.GoodTypeService;
import com.sdkj.service.system.UserService;

/** 
 * 类名称：ApplyGetMaterialsController
 * 创建人：FH 
 * 创建时间：2017-05-25
 */
@Controller
@RequestMapping(value="/applygetmaterials")
public class ApplyGetMaterialsController extends BaseController {
	
	String menuUrl = "applygetmaterials/list.do"; //菜单地址(权限用)
	@Resource(name="applygetmaterialsService")
	private ApplyGetMaterialsService applygetmaterialsService;
	@Resource(name="goodtypeService")
	private GoodTypeService goodTypeService;
	@Resource(name="applygetmaterialsdetailService")
	private ApplyGetMaterialsDetailService applygetmaterialsdetailService;
	@Resource(name="userService")
	private UserService userService;
	
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public ModelAndView save() throws Exception{
		logBefore(logger, "新增ApplyGetMaterials");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		User user=getCurrentUser();
		String primaryKey=this.get32UUID();
		pd.put("apply_get_materials_id", primaryKey);	//主键
		pd.put("user_id",user.getUSER_ID());
		pd.put("company_id",user.getCompanyId());
		pd.put("department_id",user.getDepartmentId());
		pd.put("filiale_id", user.getCompanyId());	//分公司id
		pd.put("create_time", Tools.date2Str(new Date()));	//创建时间
		pd.put("apply_type", 0);	//申请类型
		pd.put("check_state", 0);	//审核状态
		pd.put("pay_state", 0);	//支付状态
		pd.put("get_state", 0);	//领取状态
		applygetmaterialsService.save(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 审核
	 */
	@RequestMapping(value="approve")
	public void approve(HttpServletResponse response) throws Exception{
		logBefore(logger, "审核");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return;} //校验权限
		PageData pd = new PageData();
		try {
			pd = this.getPageData();
			String comment = "";
			if("yes".equals(pd.getString("flag"))||"yes" == pd.getString("flag")){
				comment = "[同意] " + pd.getString("comment");
				String taskDefKey = pd.getString("task_def_key");
				if("applymaterials_end".equals(taskDefKey)){
					pd.put("check_state", 1);
				}
			}else{
				comment = "[驳回] " + pd.getString("comment");
				pd.put("check_state", 2);
			}
			pd.put("comment", comment);
			pd.put("user_id", getCurrentUser().getUSER_ID());
			applygetmaterialsService.updateStateById(pd);
			JSONObject json = new JSONObject();
			json.put("msg","success");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.write(json.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
	}
	
	
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除ApplyGetMaterials");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			applygetmaterialsService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit() throws Exception{
		logBefore(logger, "修改ApplyGetMaterials");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData pdApply = new PageData();
		pdApply.put("apply_get_materials_id", pd.getString("apply_get_materials_id"));
		pdApply.put("account", pd.getString("account"));
		pdApply.put("remark", pd.getString("remark"));
		applygetmaterialsService.edit(pdApply);
		
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "列表ApplyGetMaterials");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return null;
		} // 校验权限
		int rank = 0;// 查看级别
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_zj")) {
			rank=0;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_dept")) {
			rank=1;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_company")) {
			rank=2;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			User user=getCurrentUser();
			pd = this.getPageData();
			pd.put("userId", user.getUSER_ID());
			pd.put("rank", rank);
			pd.put("deptId", user.getDepartmentId());
			pd.put("companyId", user.getCompanyId());
			String keyword=pd.getString("keyword");
			String lastLoginStart=pd.getString("lastLoginStart");
			String lastLoginEnd=pd.getString("lastLoginEnd");
			String check_state=pd.getString("check_state");
			String pay_state=pd.getString("pay_state");
			String get_state=pd.getString("get_state");
			if(null!=keyword&&!"".equals(keyword)){
				pd.put("keyword", keyword.trim());
			}else{
				pd.put("keyword", null);
			}
			if(null==lastLoginStart || "".equals(lastLoginStart)){
				pd.put("lastLoginStart",null);
			}
			if(null==lastLoginEnd || "".equals(lastLoginEnd)){
				pd.put("lastLoginEnd",null);
			}
			if("-1".equals(check_state)){
				pd.put("check_state",null);
			}
			if("-1".equals(pay_state)){
				pd.put("pay_state",null);
			}
			if("-1".equals(get_state)){
				pd.put("get_state",null);
			}
			page.setPd(pd);
			List<PageData>	varList = applygetmaterialsService.list(page);	//列出ApplyGetMaterials列表
			System.out.println(varList.size());
			if(varList!=null&& varList.size()>0&& varList.get(0)==null){//联表查询无数据处理
				varList=null;
			}
			mv.setViewName("materials/getmaterials/applygetmaterials_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增ApplyGetMaterials页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			Page page = new Page();
			PageData pdType = new PageData();
			pdType.put("type", "1");
			pdType.put("use_state", "0");
			page.setPd(pdType);
			List<PageData> types=goodTypeService.list(page);
			mv.setViewName("materials/getmaterials/applygetmaterials_add");
			mv.addObject("msg", "save");
			mv.addObject("types", types);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(){
		logBefore(logger, "去修改ApplyGetMaterials页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = applygetmaterialsService.findById(pd);	//根据ID读取
			Page page = new Page();
			page.setPd(pd);
			List<PageData> detailList=applygetmaterialsdetailService.list(page);
			Page pageType = new Page();
			PageData pdType = new PageData();
			pdType.put("type", "1");
			pdType.put("use_state", "0");
			pageType.setPd(pdType);
			List<PageData> types=goodTypeService.list(pageType);
			mv.setViewName("materials/getmaterials/applygetmaterials_edit");
			mv.addObject("types", types);
			mv.addObject("msg", "edit");
			mv.addObject("detailList", detailList);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	/**
	 * 去详情页面
	 */
	@RequestMapping(value="/goDetail")
	public ModelAndView goDetail(){
		logBefore(logger, "去详情ApplyGetMaterials页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = applygetmaterialsService.findById(pd);	//根据ID读取
			Page page = new Page();
			page.setPd(pd);
			List<PageData> detailList=applygetmaterialsdetailService.list(page);
			mv.setViewName("materials/getmaterials/applygetmaterials_detail");
			mv.addObject("msg", "save");
			mv.addObject("detailList", detailList);
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	
	/**
	 * 去填写领取通知页面
	 */
	@RequestMapping(value="/goIssueInfrom")
	public ModelAndView goIssueInfrom(Page page){
		logBefore(logger, "去填写领取通知页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			mv.setViewName("materials/getmaterialsinform/getmaterials_inform_add");
			mv.addObject("msg", "issueInfrom");
			mv.addObject("pd", pd);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 填写领取通知
	 */
	@RequestMapping(value="/issueInfrom")
	public ModelAndView issueInfrom(Page page){
		logBefore(logger, "发送领取通知");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			pd.put("get_state", "1");//领取状态 0等待通知 1待领取 2已领取
			pd.put("inform_create_time", Tools.date2Str(new Date()));	//创建时间
			applygetmaterialsService.updateState(pd);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 去填写领取人信息页面
	 */
	@RequestMapping(value="/goFillPerson")
	public ModelAndView goFillPerson(Page page){
		logBefore(logger, "去填写领取人信息页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			PageData obj=applygetmaterialsService.findById(pd);
			mv.setViewName("materials/getmaterialsinform/getmaterials_user_add");
			mv.addObject("msg", "fillPerson");
			mv.addObject("pd", obj);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 填写领取人信息
	 */
	@RequestMapping(value="/fillPerson")
	public void fillPerson(HttpServletResponse response){
		logBefore(logger, "填写领取人信息");
		PageData pd = new PageData();
		try{
			JSONObject arr = new JSONObject();
			pd = this.getPageData();
			String personNum=pd.getString("personNum");//工号
			PageData paUser=new PageData();
			paUser.put("NUMBER", personNum);
			PageData user=userService.findByUN(paUser);//通过编号查人员信息
			if(user==null){
				arr.put("status", false);
				arr.put("msg","该工号不存在!请核对");
			}else{
				String USER_ID=user.getString("USER_ID");
				String department_id="1";
				pd.put("get_state", "2");//领取状态 0等待通知 1待领取 2已领取
				pd.put("get_user_id", USER_ID);
				pd.put("get_department_id", department_id);
				pd.put("get_time", Tools.date2Str(new Date()));	//创建时间
				applygetmaterialsService.updateState(pd);
				arr.put("status", true);
				arr.put("msg","成功");
			}
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			String json = arr.toString();
			out.write(json);
			out.flush();
			out.close();
			
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	
	
	
	
	
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除ApplyGetMaterials");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "dell")){return null;} //校验权限
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				applygetmaterialsService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出ApplyGetMaterials到excel");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("");	//1
			titles.add("");	//2
			titles.add("");	//3
			titles.add("");	//4
			titles.add("");	//5
			titles.add("");	//6
			titles.add("");	//7
			titles.add("");	//8
			titles.add("");	//9
			titles.add("");	//10
			dataMap.put("titles", titles);
			List<PageData> varOList = applygetmaterialsService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("apply_get_materials_id"));	//1
				vpd.put("var2", varOList.get(i).getString("project_id"));	//2
				vpd.put("var3", varOList.get(i).getString("apply_user_name"));	//3
				vpd.put("var4", varOList.get(i).getString("user_section"));	//4
				vpd.put("var5", varOList.get(i).getString("create_time"));	//5
				vpd.put("var6", varOList.get(i).getString("check_state"));	//6
				vpd.put("var7", varOList.get(i).getString("pay_state"));	//7
				vpd.put("var8", varOList.get(i).getString("get_state"));	//8
				vpd.put("var9", varOList.get(i).getString("get_user_name"));	//9
				vpd.put("var10", varOList.get(i).getString("get_user_section"));	//10
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
}
